import os
import time

import openpyxl
import yaml
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait


class BoxDriver:

    def __init__(self,imgs,browser='Chrome'):
        if browser == 'Chrome':
            self.driver = webdriver.Chrome()
        elif browser == 'Firefox':
            self.driver = webdriver.Firefox()
        elif browser == 'Ie':
            self.driver = webdriver.Ie()
        elif browser == 'Edge':
            self.driver = webdriver.Edge()
        elif browser == 'Safari':
            self.driver = webdriver.Safari()
        elif browser == 'Opera':
            self.driver = webdriver.Opera()

        self.driver.get('https://dashboard-mng.bilibili.co/login.html?caller=ad-biligame')
        self.driver.maximize_window()
        # 隐式等待
        self.driver.implicitly_wait(10)

        self.imgs = imgs


    # 访问url
    def open(self,url):
        # 打开网页 url网页的地址
        self.driver.get(url)


    def maximize_window(self):
        '''
        窗口最大化
        '''
        self.driver.maximize_window()

    def implicitly_wait(self, seconds=10):
        '''
        隐式等待
        seconds 最大等待时间，单位是秒
        '''
        self.driver.implicitly_wait(seconds)

    def webdriver_wait(self, selector):
        '''
        显示等待
        selector    自定义的定位方式
        '''
        # 获取元素的定位方式
        locator = self.convert_selector_to_locator(selector)
        # 等待
        return WebDriverWait(self.driver, 10, 0.5).until(expected_conditions.presence_of_element_located(locator))


    def convert_selector_to_locator(self,selector):
        '''
        将自定义的定位方式转换为Selenium的标准定位方式
        'id,account'  -> (By.ID, 'account')
        selector    自定义的定位方式
        '''
        # 拆分字符串
        by,value = selector.split(',')
        # 去除多余的空格
        by,value = by.strip(),value.strip()
        if by == 'id' or by == 'i':
            locator = (By.ID,value)
        elif by == 'name' or by == 'n':
            locator = (By.NAME,value)
        elif by == 'class_name' or by == 'c':
            locator = (By.CLASS_NAME,value)
        elif by == 'tag_name' or by == 't':
            locator = (By.TAG_NAME,value)
        elif by == 'link_text' or by == 'l':
            locator = (By.LINK_TEXT,value)
        elif by == 'partial_link_text' or by == 'p':
            locator = (By.PARTIAL_LINK_TEXT,value)
        elif by == 'xpath' or by == 'x':
            locator = (By.XPATH,value)
        elif by == 'css_selector' or by == 'css':
            locator = (By.CSS_SELECTOR,value)
        return locator

    def locate_element(self,selector):
        '''
        定位单个元素
        selector    自定义的定位方式
        '''
        # 将自定义定位方式转换为标准定位饭方式
        locator = self.convert_selector_to_locator(selector)
        # 返回定位到的元素
        return self.driver.find_element(*locator)

    def locate_elements(self,selector):
        '''
        定位多个元素
        selector    自定义的定位方式
        '''
        # 将自定义定位方式转换为标准定位饭方式
        locator = self.convert_selector_to_locator(selector)
        # 返回定位到的元素
        return self.driver.find_elements(*locator)


    # driver.find_element(By.CSS_SELECTOR,"[placeholder='输入价格']")
    def find_element(self,s2):
        return self.driver.find_element(By.CSS_SELECTOR,s2)

    # 截图
    def get_screenshort_as_file(self,sc):
        return self.driver.get_screenshot_as_file(sc)

    # 调整屏幕分辨率
    def set_window_size(self,s6,s7):
        return self.driver.set_window_size(s6,s7)

    def input(self,selector,text):
        '''
        向元素中写入文本
        selector    自定义的定位方式
        text        文本
        '''
        # 定位元素
        element = self.locate_element(selector)
        # 清空
        element.clear()
        # 写入文本
        element.send_keys(text)

    def click(self,selector):
        '''
        向元素中写入文本
        selector    自定义的定位方式
        '''
        # 定位元素
        element = self.locate_element(selector)
        # 单击
        element.click()

    def switch_to_frame(self,selector):
        '''
        进入frame
        selector    自定义的定位方式
        '''
        # 定位iframe元素
        iframe = self.locate_element(selector)
        # 切换到iframe中
        self.driver.switch_to.frame(iframe)

    def switch_to_window(self,handle):
        #handles = self.driver.window_handles
        self.driver.switch_to.window(handle)

    def handles(self):
        return self.driver.window_handles

    def current_url(self):
        return self.driver.current_url

    # 调整分辨率
    def execute_script(self,c1):
        return self.driver.execute_script(c1)

    # 修改js属性，对于元素不点击
    def execute_scripts(self,c11,c12):
        return self.driver.execute_script(c11,c12)

    def add_img(self):
        # self.logs.logger.info('获取当前窗口的截图保存为一个base64编码的字符串。')
        return self.driver.get_screenshot_as_base64()  # 获取当前窗口的截图保存为一个base64编码的字符串。

    def getImage(self):
        #截的图保存在screen文件夹中
        timestamp = time.strftime('%Y-%m-%d_%H-%M-%S')
        imgPath = os.path.join('C:\codes\POM\screen', '%s.png'%(timestamp))
        #print('screenshot:', timestamp, '.png')
        self.driver.save_screenshot(imgPath)
        return print('screenshot:', timestamp, '.png')

    def save_screenshot(self,ss):
        return self.driver.save_screenshot(ss)

    def select_by_index(self,selector,index):
        '''
        根据下标进行选择
        selector    自定义的定位方式
        index       下标
        '''
        select = self.locate_element(selector)
        depts = Select(select)
        depts.select_by_index(index) # 根据下标进行选择，下标从0开始

    def select_by_value(self,selector,value):
        '''
        根据value属性的值进行选择
        selector    自定义的定位方式
        value       value属性的值
        '''
        select = self.locate_element(selector)
        depts = Select(select)
        depts.select_by_value(value) # 根据下标进行选择，下标从0开始

    def select_by_visible_text(self,selector,visible_text):
        '''
        根据可见文本进行选择
        selector    自定义的定位方式
        visible_text   可见文本
        '''
        pass
        select = self.locate_element(selector)
        depts = Select(select)
        depts.select_by_visible_text(visible_text) # 根据下标进行选择，下标从0开始


    def close(self):
        '''
        关闭当前窗口
        '''
        self.driver.close()

    def quit(self):
        '''
        退出浏览器
        '''
        self.driver.quit()



class BasePage:

    def __init__(self,driver:BoxDriver):
        self.driver = driver

    @staticmethod
    def get_yaml(url):
        '''
        读取yaml格式的文件，并将内容封装为字典返回
        url     文件地址
        '''
        with open(url,'r',encoding='utf-8') as file:
            return yaml.safe_load(file.read())


    @staticmethod   #静态方法
    def get_excel(file,sheet):
        '''
        从excel工作簿中获取数据，并封装为下面的格式
        [('admin','123456'),('user0','123456'),('user1','123456')]
        file    工作簿地址
        sheet   工作表名称
        '''
        # 打开工作簿
        workbook = openpyxl.load_workbook(file)
        # 打开工作表
        worksheet = workbook[sheet]
        # 获取取单元格
        # return [row for row in worksheet.values][1:]
        return list(worksheet.values)[1:]


if __name__ == '__main__':
    imgs = []
    BoxDriver(imgs).convert_selector_to_locator('xpath,user')

